<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/3 0003
 * Time: 12:01
 */

namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Exception;
use Yansongda\Pay\Pay;
use think\Request;
class Pays extends Controller
//class Pays
{

    protected $config = [
        'alipay' => [
            'app_id' => '2018070360505240',
            'notify_url' => 'http://47.96.230.76/pays/alipay',
            'private_key'=>'MIIEpAIBAAKCAQEA8iETCD/Yr1ow10qw83yC8PnY1xjwS3+0exqvGDHibFbNAXbkBYWEWFFjahvK35Jl2qp5q5ntD62FeoWyFEMRUMqQ0OlQJRhu/MxLvrfFwIP5lluko15zZTJGN0jo9quXw62KBQLcA/ngwW3xxTEYkvhZCn37EoKLiYwiSC+x7caJvnc7FLsXQYaIH2p47Ly0RPC2f1OjPzAKV75mJnpGNYvT6+BYNC5Ba9PXfh5VJs8LoCqe/ivS3a5F/iFNBziUFStY2Hep3isrNr8Y5zYUC1ZndUWsF/P9VZOKAEp6MWiTb6f9qtsHSGzcEZFTc9px7+cX0Os3BgFZieXfLzwCewIDAQABAoIBABNVYsCo4HN3/yhhtWlrysTVHmRmgGF27AFcaxjCevLtp2bziFeMhrnKneaOG4/oj6t7K0Xxf4Vd9KeI32RQyqQp2JBl4Nllbw9OfMnYwLiTkS1ZWfcVhp9Q+VxWvQtdPjwIslmeFdVXcYPgdIqrVev+WpXE43Rh6iRshRxAerOim/7nWLA0oEkudQUA+ZXLIuBBCKZKuS/DBH4maCXhH8HltzoznS5gzW30PCl6oJdwOw5lauvAnIiMEXS4T6kxH9fuvPonjsbqvbVK5q6qgMDIdcW3yB+nJ3dEz9Hs9DZVbu4OAaSlFyL1yHmpL36/yxubtbtCFAktvo23PQG/AfkCgYEA/X+xj1rxLkf0PU/LR/8McocEEFOWHbYAL/UNaaz9tnIJi0iDStPYMd2y6JWQjIDtDj+/WtgXYHllFDGwZWmY3385CI5Dt6ZC6tGv0Wo3v2ly5FSpcas4QM77Hpw4t8Pu9GqSsuItV0ZpaL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VLcy4VgtMgj/JTVSbRdxOGTT6x69gNBhSsow8VdO9kN5ie9TH64TCcGXlUwIDAQAB',
        ],
        'wechat' => [
            'appid' => 'wxeaf95bb1512c77d4',//懂婚礼
            'mch_id' => '1510472101',//商户号
            'notify_url' => 'http://47.96.230.76/pays/wechat',//回调地址
            'key' => 'ABCD1234abcd123456donghunli12345',//商户key
        ],
    ];
    public function index()
    {
        $data = input('post.');
//        $user_id = $this->user_id;
//        if ($data['way'] == 'agent'){
//            $is_agent = Db::name('users')->where('user_id',$user_id)->value('is_agent');
//            if ($is_agent == 1) api_return(0,'您已经是代理了');
//            $price = Db::name('extend')->where('id',1)->value('agent');
//            $title = '购买代理';
//        }elseif($data['way'] == 'credit'){
//            $cache = cache('credit'.$this->user_id);
//            if ($cache) api_return(0,'您的信用评分还未过期');
//            $title = '信用评分查询';
//            $price = Db::name('extend')->where('id',1)->value('price');
//        }else{
//            api_return(0,'付款标识错误');
//        }

//        if ($price < 0.01) api_return(0,'支付金额错误');
        if ($data['type'] == 'wxpay'){
            $config_biz = [
                'out_trade_no' =>  'DaiKe'.date('Ymdhis').$user_id.rand(111,999),//订单号
                'total_fee' =>  $price * 100, // **单位：分**
//                'total_fee' =>  1, // **单位：分**
                'attach'=> $user_id.','.$data['way'],
                'body' => $title,
            ];
            $pay = new Pay($this->config);
            $result = $pay->driver('wechat')->gateway('app')->pay($config_biz);
            api_return(1,'获取成功',$result);
        }else if ($data['type'] == 'alipay'){
            $config_biz = [
                'out_trade_no' =>  'DaiKe'.date('Ymdhis').$user_id.rand(111,999),
                'total_amount' => $price,
//                'total_amount' => 0.01,
                'subject'      => $title,
                'body' => $user_id.','.$data['way'],
            ];
            $pay = new Pay($this->config);
            $result =  $pay->driver('alipay')->gateway('app')->pay($config_biz);
            $row = str_replace('&return_url=','',$result);
            api_return(1,'获取成功',$row);
        }
        api_return(0,'参数错误');
    }

    public function wechat(Request $request)
    {
        $pay = new Pay($this->config);
        $verify = $pay->driver('wechat')->gateway('app')->verify($request->getContent());//验证签名
        if ($verify) {
            //如果验证成功
            Db::startTrans();
            try{
                /*$data['price'] = $verify['cash_fee'] / 100;
                $data['out_trade_no'] = $verify['out_trade_no'];
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['trade_no'] = $verify['transaction_id'];
                $data['type'] = 'wxpay';
                $data['status'] = 1;
                $attach = explode(',',$verify['attach']);
                $data['user_id'] = $attach[0];
                $type = $attach[1];*/
                if ($type == 'agent'){
                    $data['remark'] = '开通代理交易成功';
                    //改变会员状态
                    Db::name('users')->where('user_id',$data['user_id'])->update(['is_agent'=>1]);
                    //返利
                    $this->rebate($data['user_id']);
                }else{
                    $max = $this->credit($data['user_id']);
                    if ($max){
                        $data['remark'] = '信用分查询成功';
                        $fan = Db::name('extend') ->where('id',1)->value('fan');
                        //TODO  是否添加消息推送
                        $user_id = Db::name('users')->where('user_id',$data['user_id'])->value('proxy_id');
                        if ($user_id){
                            Db::name('users')->where('user_id',$user_id)->setInc('money',$fan);
                            Db::name('users')->where('user_id',$user_id)->setInc('total',$fan);
                            Cash($user_id,$fan,'数据查询');
                        }
                    }else{
                        $data['remark'] = '信用分查询失败';
                    }
                }
                Db::name('order')->insert($data);
                Db::commit();
            }catch (Exception $e){
                file_put_contents('wechat.txt', $e."\r\n", FILE_APPEND);
                Db::rollback();
            }
        }
        echo "success";
    }

    public function alipay()
    {

        $pay = new Pay($this->config);
        $verify = $pay->driver('alipay')->gateway('app')->verify(input('post.'));

//        $verify  = cache('test102');
        if ($verify) {
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为 out_trade_no 这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_idller_email）；
            // 4、验证app_id是否为该商户本身。
            if($verify['trade_status']!='TRADE_SUCCESS'&&$verify['trade_status']!='TRADE_FINISHED'){
                file_put_contents('alipayerror.txt',$verify['out_trade_no']);
                echo "success";exit;//支付 失败
            }else{
                Db::startTrans();
                try{
                    $data['price'] = $verify['total_amount'];
                    $data['out_trade_no'] = $verify['out_trade_no'];
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $data['trade_no'] = $verify['trade_no'];
                    $data['type'] = 'alipay';
                    $data['status'] = 1;
                    $attach = explode(',',$verify['body']);
                    $data['user_id'] = $attach[0];
                    $type = $attach[1];
                    if ($type == 'agent'){
                        $data['remark'] = '开通代理交易成功';
                        //改变会员状态
                        Db::name('users')->where('user_id',$data['user_id'])->update(['is_agent'=>1]);
                        //返利
                        $this->rebate($data['user_id']);
                    }else{
                        $max = $this->credit($data['user_id']);
                        if ($max){
                            $data['remark'] = '信用分查询成功';
                            $user_id = Db::name('users')->where('user_id',$data['user_id'])->value('proxy_id');
                            if ($user_id){
                                $fan = Db::name('extend') ->where('id',1)->value('fan');
                                //TODO  是否添加消息推送
                                Db::name('users')->where('user_id',$user_id)->setInc('money',$fan);
                                Db::name('users')->where('user_id',$user_id)->setInc('total',$fan);
                                //账户明细
                                Cash($user_id,$fan,'数据查询');
                            }
                        }else{
                            $data['remark'] = '信用分查询失败';
                        }
                    }
                    Db::name('order')->insert($data);
                    Db::commit();
                }catch (Exception $e){
                    file_put_contents('alipay.txt', $e."\r\n", FILE_APPEND);
                    Db::rollback();
                }
                echo "success";exit;
            }
        } else {
            file_put_contents('alipay.txt',"Error Number:-10021, Error Description: ER_VERIFY_ERROR（验签失败）|".openssl_error_string());
            file_put_contents('alipay.txt', "收到支付宝异步通知：".input('trade_no')."\r\n", FILE_APPEND);
            file_put_contents('alipay.txt', openssl_error_string()."\r\n", FILE_APPEND);
        }
        file_put_contents('log.txt', openssl_error_string()."\r\n", FILE_APPEND);
        echo "success";exit;
    }





    protected function rebate($user_id = 0){
        //一级代理返点
        $A = Db::name('users')->where('user_id',$user_id)->value('proxy_id');
        if (!empty($A)){
            $ratio = Db::name('extend')->where('id',1)->field('A_rebate,B_rebate,C_rebate')->find();
            Db::name('users')->where('user_id',$A)->setInc('money',$ratio['A_rebate']);
            Db::name('users')->where('user_id',$A)->setInc('total',$ratio['A_rebate']);
            //账户明细
            Cash($A,$ratio['A_rebate'],'1级代理返佣');
            //二级代理
            $B = Db::name('users')->where('user_id',$A)->value('proxy_id');
            if (!empty($B)){
                Db::name('users')->where('user_id',$B)->setInc('money',$ratio['B_rebate']);
                Db::name('users')->where('user_id',$B)->setInc('total',$ratio['B_rebate']);
                //账户明细
                Cash($B,$ratio['B_rebate'],'2级代理返佣');
                //三级代理返点
                $C = Db::name('users')->where('user_id',$B)->value('proxy_id');
                if ($C){
                    Db::name('users')->where('user_id',$C)->setInc('money',$ratio['C_rebate']);
                    Db::name('users')->where('user_id',$C)->setInc('total',$ratio['C_rebate']);
                    //账户明细
                    Cash($C,$ratio['C_rebate'],'3级代理返佣');}
            }
        }
    }


    /**
     * 信用评分查询
     */
    private function credit($user_id)
    {
        $user = Db::name('users')->where('user_id',$user_id)->field('real_name,ID,phone')->find();
        $map['name'] =  $user['real_name'];//孟凡滨
        $map['idCard'] = $user['ID'];//370883197510293916
        $map['phone'] =  $user['phone'];//13953747125
        $map['appkey'] = config('JD.appkey');
        $result = curl_post(config('JD.url'),$map);
        $data = json_decode($result,true);
        if ($data['code'] == 10000 && $data['charge']){
            $max = $data['result']['data']['user_basic'];
            $max['blacklist_name_with_phone'] = $data['result']['data']['user_blacklist']['blacklist_name_with_phone'];
            $max['blacklist_name_with_idcard'] = $data['result']['data']['user_blacklist']['blacklist_name_with_idcard'];
            $max['contacts_class1_blacklist_cnt'] = $data['result']['data']['user_gray']['contacts_class1_blacklist_cnt']??0;
            $max['contacts_class2_blacklist_cnt'] = $data['result']['data']['user_gray']['contacts_class2_blacklist_cnt']??0;
            $max['phone_gray_score'] = $data['result']['data']['user_gray']['phone_gray_score']??60;
            $max['contacts_class1_cnt'] = $data['result']['data']['user_gray']['contacts_class1_cnt']??0;
            $max['user_searched_history_by_orgs'] = $data['result']['data']['user_searched_history_by_orgs'];
            $time = Db::name('extend')->where('id',1)->value('end_time');
            cache('credit'.$user_id,$max,86400*$time);
            return true;
        }else{
            return false;
        }
    }


}











